package com.tyler.redis;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author: TylerZhong
 * @description:
 */
public class MyRedisClient {
    OutputStream write;
    InputStream reader;

    public MyRedisClient(String host, int port) throws IOException {
        Socket socket = new Socket(host, port);
        write = socket.getOutputStream();
        reader = socket.getInputStream();
    }

    public String auth(String password) throws IOException {
        StringBuffer command = new StringBuffer();
        command.append("*2").append("\r\n"); //参数数量
        command.append("$4").append("\r\n"); //第一个参数长度
        command.append("AUTH").append("\r\n"); //第一个参数值

        //socket编程需要关注二进制长度。
        command.append("$").append(password.getBytes().length).append("\r\n");//第二个参数长度
        command.append(password).append("\r\n"); //第二个参数值


        //2 发送报文到
        write.write(command.toString().getBytes());
        //3 接收redis响应
        byte[] response = new byte[1024];
        reader.read(response);

        return new String(response);
    }

    public String set(String key, String value) throws IOException {
        StringBuffer command = new StringBuffer();
        command.append("*3").append("\r\n");
        command.append("$3").append("\r\n");
        command.append("SET").append("\r\n");

        command.append("$").append(key.getBytes().length).append("\r\n");
        command.append(key).append("\r\n");

        command.append("$").append(value.getBytes().length).append("\r\n");
        command.append(value).append("\r\n");

        write.write(command.toString().getBytes());
        byte[] response = new byte[1024];
        reader.read(response);

        return new String(response);
    }

    public static void main(String[] args) throws IOException {
        MyRedisClient redisClient = new MyRedisClient("192.168.56.154", 6379);
//        System.out.println(redisClient.auth("root"));
        System.out.println(redisClient.set("k5", "v5"));
    }
}
